<?php

require_once BaseUtil::getModulePath ( "dbgrid" ) . '/DBGrid.php';
require_once BaseUtil::getModulePath ( "dbgrid" ) . '/DBGridConstant.php';
require_once BaseUtil::getModulePath ( "base" ) . '/services/BaseService.php';
require_once BaseUtil::getModulePath ( "order" ) . '/models/OrderDao.php';
require_once BaseUtil::getModulePath ( "order" ) . '/models/OrderItemsDao.php';
require_once BaseUtil::getModulePath ( "order" ) . '/models/OrderPackageItemsDao.php';
require_once BaseUtil::getModulePath ( "order" ) . '/models/OrderPackageDao.php';
require_once BaseUtil::getModulePath ( "order" ) . '/models/AddressDao.php';
require_once BaseUtil::getModulePath ( "inventory" ) . '/models/ProductItemDao.php';
require_once BaseUtil::getModulePath ( "component" ) . '/Number.php';
require_once BaseUtil::getModulePath("customer")  .  '/models/CustomerDao.php';
require_once BaseUtil::getModulePath("order")  .  '/models/OrderJournalDao.php';

class OrderService extends BaseService {
	
	private $orderDao;
	private $orderItemsDao;
	private $orderPackageItemsDao;
	private $addressDao;
	private $orderPackageDao;
	private $productItemDao;
	private $customerDao;
	private $orderJournalDao;
	
	public function __construct() {
		parent::__construct ();
		$this->orderDao = new OrderDao ( );
		$this->orderDao->setDb ( $this->db );
		
		$this->orderItemsDao = new OrderItemsDao ( );
		$this->orderItemsDao->setDb ( $this->db );
		
		$this->orderPackageItemsDao = new OrderPackageItemsDao ( );
		$this->orderPackageItemsDao->setDb ( $this->db );
		
		$this->orderPackageDao = new OrderPackageDao ( );
		$this->orderPackageDao->setDb ( $this->db );
		
		$this->addressDao = new AddressDao ( );
		$this->addressDao->setDb ( $this->db );
		
		$this->productItemDao = new ProductItemDao ( );
		$this->productItemDao->setDb ( $this->db );
		
		$this->customerDao = new CustomerDao ( );
        $this->customerDao->setDb ( $this->db );
        
        $this->orderJournalDao = new OrderJournalDao();
        $this->orderJournalDao->setDb( $this->db );
	}
	
	public function getOrderById($id) {
		$order = $this->orderDao->getOrderById ( $id );
		return $order;
	}
	
	public function getOrderAllById($id) {
		return $this->orderDao->getAllById ( $id );
	}
	
	public function getOrderItemsById($id) {
		$result = $this->orderItemsDao->getItemsById ( $id );
		return $result;
	}
	
	public function getPackageItemsByPlace($id) {
	
	}
	
	public function getPackageItemsById($ids, $orderId) {
		$items = array ();
		foreach ( $ids as $id ) {
			$item = $this->orderItemsDao->getItemById ( $id );
			$num = $this->orderPackageItemsDao->getItemsQtyById ( $id );
			$item ['quantity'] -= $num;
			$items [] = $item;
		}
		return $items;
	}
	
	public function getItemsByPackageId($id) {
		$items = $this->orderPackageItemsDao->getItemsById ( $id );
		return $items;
	}
	
	public function getPackageById($id) {
		return $this->orderPackageDao->getByCol ( "id", $id );
	}
	
	public function addPackage($package, $items) {
		$packageId = $this->orderPackageDao->addPackage ( $package );
		foreach ( $items as $key => $item ) {
			$item ['order_package_id'] = $packageId;
			$this->orderPackageItemsDao->addItem ( $item );
		}
	}
	
	public function editPackage($id, $package, $items) {
		$this->orderPackageDao->updatePackage ( $id, $package );
		foreach ( $items as $key => $item ) {
			$itemId = $item ['id'];
			unset ( $item ['id'] );
			$this->orderPackageItemsDao->updateItem ( $itemId, $item );
		}
	}
	
	public function delPackage($id) {
		$package = $this->getPackageById ( $id );
		$status = $package ['status'];
		if ($status == 0) {
			$this->orderPackageDao->deletePackage ( $id );
			$this->orderPackageItemsDao->delItemsBypackageId ( $id );
		}
	}
	
	public function getPackagesById($orderId) {
		$result = array ();
		$packages = $this->orderPackageDao->getPackages ( $orderId );
		foreach ( $packages as $package ) {
			$items = $this->getItemNumByPackageId ( $package ['id'] );
			foreach ( $items as $item ) {
				$package ['item'] [$item ['order_item_id']] = $item ['quantity'];
			}
			$result [] = $package;
		}
		return $result;
	}
	
	public function getItemNumByPackageId($packageId) {
		return $this->orderPackageItemsDao->getItemNumsById ( $packageId );
	}
	
	public function getOrders($view, $post) {
		$selectOptions = array ("0" => $this->_translate->translate ( 'noLabel' ), "1" => $this->_translate->translate ( 'yesLabel' ) );
		$dbGrid = new DBGrid ( $view );
		$dbGrid->setPost ( $post );
		$dbGrid->setSortOrder("created","desc");
		$dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "orders-id", $this->_translate->translate ( "orderID" ) );
		$dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "orders-order_num", $this->_translate->translate ( "orderno" ) );
		$dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "u1-name", $this->_translate->translate ( "orderUser" ) );
		$dbGrid->addOptionsFilter ( DBGridConstant::FILTER_TYPE_SELECT, "orders-status", $this->_translate->translate ( "status" ), OrderConstant::getStatusList ()  );
        $dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "u2-name", $this->_translate->translate ( "agentName" ) );
		$dbGrid->addDateFilter("orders-created", $this->_translate->translate("orderTime"));
        
        $dbGrid->addFetchTable ( "orders", "*" );
		$dbGrid->addFetchTable ( "users as u1", "u1.name as user_name","u1.id = orders.user_id" );
		$dbGrid->addFetchTable ( "users as u2", "u2.name as agent_name","u2.id = orders.agent_id",DBGridConstant::JOIN_TYPE_OUTER );
		$dbGrid->addValueFilter ( "orders-is_delete", "0" );
	    $dbGrid->addValueFilter ( "orders-is_returned", "0" );
	    $dbGrid->addFetchColumn ( "id", $this->_translate->translate ( "orderID" ), "edit" );
		$dbGrid->addFetchColumn ( "order_num", $this->_translate->translate ( "orderno" ));
		$dbGrid->addFetchColumn ( "status", $this->_translate->translate ( "status"), "", OrderConstant::getStatusList ()  );
		$dbGrid->addFetchColumn ( "user_name", $this->_translate->translate ( "orderUser" ) );
		$dbGrid->addFetchColumn ( "agent_name", $this->_translate->translate ( "agentName" ) );
		$dbGrid->addFetchColumn ( "total", $this->_translate->translate ( "totalFee" ) );
		$dbGrid->addFetchColumn ( "created", $this->_translate->translate ( "orderTime" ) );
		$dbGrid->setPageTitle ( $this->_translate->translate ( "orderList" ) );
		$dbGrid->setModule ( '/order/order' );
		return $dbGrid->render ();
	}
	public function getReturnOrders($view, $post) {
		$selectOptions = array ("0" => $this->_translate->translate ( 'noLabel' ), "1" => $this->_translate->translate ( 'yesLabel' ) );
		$dbGrid = new DBGrid ( $view );
		$dbGrid->setPost ( $post );
		$dbGrid->setSortOrder("created","desc");
		$dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "orders-id", $this->_translate->translate ( "orderID" ) );
		$dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "orders-order_num", $this->_translate->translate ( "orderno" ) );
		$dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "u1-name", $this->_translate->translate ( "orderUser" ) );
		$dbGrid->addOptionsFilter ( DBGridConstant::FILTER_TYPE_SELECT, "orders-is_returned", $this->_translate->translate ( "returnStatus" ) ,array(1=>$this->_translate->translate ( "returnStatus_1"),2=>$this->_translate->translate ( "returnStatus_2")));
		$dbGrid->addOptionsFilter ( DBGridConstant::FILTER_TYPE_SELECT, "orders-status", $this->_translate->translate ( "status" ), OrderConstant::getStatusList ()  );
         $dbGrid->addFilter ( DBGridConstant::FILTER_TYPE_TEXT, "u2-name", $this->_translate->translate ( "agentName" ) );
		$dbGrid->addDateFilter("orders-created", $this->_translate->translate("orderTime"));
		
		$dbGrid->addFetchTable ( "orders", "*" );
		$dbGrid->addFetchTable ( "users as u1", "u1.name as user_name","u1.id = orders.user_id" );
		$dbGrid->addFetchTable ( "users as u2", "u2.name as agent_name","u2.id = orders.agent_id",DBGridConstant::JOIN_TYPE_OUTER );
		$dbGrid->addValueFilter ( "orders-is_delete", "0" );
		$dbGrid->addValueFilter ( "orders-is_returned", "0",DBGridConstant::OPERATOR_NOT_EQUAL );
		$dbGrid->addFetchColumn ( "id", $this->_translate->translate ( "orderID" ), "detail" );
		$dbGrid->addFetchColumn ( "order_num", $this->_translate->translate ( "orderno" ));
		$dbGrid->addFetchColumn ( "status", $this->_translate->translate ( "status"), "", OrderConstant::getStatusList ()  );
		$dbGrid->addFetchColumn ( "is_returned", $this->_translate->translate ( "returnStatus"), "", array(1=>$this->_translate->translate ( "returnStatus_1"),2=>$this->_translate->translate ( "returnStatus_2"))  );
		$dbGrid->addFetchColumn ( "user_name", $this->_translate->translate ( "orderUser" ) );
		$dbGrid->addFetchColumn ( "agent_name", $this->_translate->translate ( "agentName" ) );
		$dbGrid->addFetchColumn ( "total", $this->_translate->translate ( "totalFee" ) );
		$dbGrid->addFetchColumn ( "created", $this->_translate->translate("orderTime") );
		$dbGrid->setPageTitle ( $this->_translate->translate ( "orderList" ) );
		$dbGrid->setModule ( '/order/order' );
		return $dbGrid->render ();
	}
	public function cancelOrderItem($id, $item) {
		$this->orderItemsDao->cancelItem ( $id, $item );
		$this->orderPackageItemsDao->delItem ( $id );
	
	}
	
	//    public function addorder($shippingaddress,$billingaddress) {
	//        $shippingid=$this->shippingAddressDao->addShippingAddress($shippingaddress);
	//        $billingid=$this->billingAddressDao->addBillingAddress($billingaddress);
	//        $ordernum=Number::getOrderNumber();
	//        $order=array(
	//                "order_num" => $ordernum,
	//                "customer_id" => $_POST['customerid'],
	//                "status" => $_POST['status'],
	//                "shipping_address_id" => $shippingid,
	//                "billing_address_id" => $billingid,
	//                "shipping_expect" => $_POST['shipping'],
	//                "payment_method" => $_POST['method']
	//        );
	//        $orderid=$this->orderDao->addOrder($order);
	//        $productid=$_POST['itemid'];
	//        // get the sale_price from product_items
	//        $sprice=$this->productItemDao->getSprice($productid);
	//        $orderitem=array(
	//                "order_id"=>$orderid,
	//                "item_id"=>$productid,
	//        // sale_price
	//                "sale_price"=>$sprice,
	//        // deal_price
	//                "deal_price"=>$sprice
	//        );
	//        $this->orderItemsDao->addOrderItem($orderitem);
	//    }
	

	public function addOrder($shippingAddress, $billingAddress, $order, $itemIds) {
		
		$shippingid = $this->shippingAddressDao->addShippingAddress ( $shippingAddress );
		$billingid = $this->billingAddressDao->addBillingAddress ( $billingAddress );
		$order ["shipping_address_id"] = $shippingid;
		$order ["billing_address_id"] = $billingid;
		$orderid = $this->orderDao->addOrder ( $order );
		//order item
		foreach ( $itemIds as $itemId ) {
			// get the sale_price from product_items
			$sprice = $this->productItemDao->getSprice ( $itemId );
			$orderitem = array ("order_id" => $orderid, "item_id" => $itemId, "sale_price" => $sprice, "deal_price" => $sprice, "quantity" => 1 );
			$this->orderItemsDao->addOrderItem ( $orderitem );
		}
		$this->checkOrder ( $orderid );
	}
	
	public function editOrder($order) {
		$msg = "";
		if (! $this->isCreatePackage ( $order ['orderId'] )) {
			$this->shippingAddressDao->updateShippingAddress ( $order ['sid'], $order ['shippingAddress'] );
			$this->billingAddressDao->updateBillingAddress ( $order ['bid'], $order ['billingAddress'] );
			$this->orderDao->updateOrder ( $order ['orderId'], $order ['order'] );
			$this->orderItemsDao->delItemsById ( $order ['orderId'] );
			foreach ( $order ['itemIds'] as $itemId ) {
				$sprice = $this->productItemDao->getSprice ( $itemId );
				$orderItem = array ("order_id" => $order ['orderId'], "item_id" => $itemId, "sale_price" => $sprice, "deal_price" => $sprice, "quantity" => 1 );
				$this->orderItemsDao->addOrderItem ( $orderItem );
			}
			$msg = "success";
			$this->checkOrder ( $order ['orderId'] );
		} else {
			$msg = "failed";
		}
		return $msg;
	}
	
	private function isCreatePackage($id) {
		$num = $this->orderPackageDao->getCountById ( $id );
		if ($num == 0) {
			return false;
		} else {
			return true;
		}
	}
	
	public function getBillingAddressById($id) {
		return $this->orderDao->getBillingAddressById ( $id );
	}
	
	public function getShippingAddressById($id) {
		return $this->orderDao->getShippingAddressById ( $id );
	}
	
	/**
	 * check order status
	 */
	private function checkOrder($orderId) {
		$order = array ("status" => 2 );
		$this->orderDao->updateOrder ( $orderId, $order );
		return true;
	}
	public function updateOrder($id, $order) {
		$this->orderDao->updateOrder ( $id, $order );
	}
	
	public function countByOrderStatus() {
		return $this->orderDao->countOrders ();
	}
	
	public function countByPackageStatus() {
		return $this->orderPackageDao->countPackages ();
	}
	
	public function returnInventoryByOrderId($orderId){
		$items = $this->orderItemsDao->getItemsByOrderId($orderId);
		if(!empty($items)){
			foreach($items as $item){
                $itemId = $item['item_id'];
                $quantity = $item['quantity'];
                $productItem = $this->productItemDao->getProductItemById($itemId);
                if(!empty($productItem)){
                	 $data = array();
                	 $data['inventory'] = intval($productItem['inventory']) + intval($quantity);
                	 $this->productItemDao->updateItem($itemId,$data);
                }			
			}
		}
	}
    
	public function getAgentId($userId){
		$user = $this->customerDao->getByCol("id",$userId);
        $id = 0;
		if($user['certf'] == 3 || $user['certf'] == 5 || $user['certf'] == 6){
			$id = $userId;
		}else if($user['certf'] == 4){
			$id = $user['parent_id'];
		}
		return $id;
	}
	
	public function getJournalByOrderId($orderId){
		return $this->orderJournalDao->getJournalByOrderId($orderId);
	}
	
	public function addJournal($journal){
		return $this->orderJournalDao->insertData($journal);
	}
	
	public function deleteJournal($journalId){
		$this->orderJournalDao->deleteJournal($journalId);
	}
}